<template>
  <div class="page-coupon-add-or-update">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{
          dataForm.comboId
            ? (pageType === 1 ? $t('combo.editCombo') : $t('combo.viewCombo'))
            : $t('combo.addCombo')
        }}
      </div>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      class="form-box"
      label-width="auto"
      @submit.prevent
    >
      <!--套餐名称-->
      <el-form-item
        :label="$t('combo.name') + ':'"
        prop="name"
      >
        <el-input
          v-model="dataForm.name"
          :disabled="pageType === 2"
          maxlength="20"
          show-word-limit
          style="width: 526px"
          class="coupon-input"
          :placeholder="$t('combo.name')"
        />
      </el-form-item>
      <!--活动时间-->
      <el-form-item
        :label="$t('marketing.activTime') + ':'"
        :required="true"
      >
        <div class="date-picker">
          <!--开始时间-->
          <el-form-item prop="startTime">
            <el-date-picker
              v-model="dataForm.startTime"
              :disabled="pageType === 2"
              type="date"
              :placeholder="$t('live.chooseStartDate')"
              value-format="YYYY-MM-DD"
              style="width:140px"
            />
            <el-time-select
              v-model="startTimeValue"
              :class="[startTimeValue ? 'select-time': '']"
              start="00:00"
              step="00:30"
              end="23:30"
              style="width:106px"
              :disabled="pageType === 2"
              :placeholder="$t('time.startTime')"
            />
          </el-form-item>
          <span style="margin: 0 10px">{{ $t('time.tip') }}</span>
          <!--结束时间-->
          <el-form-item prop="endTime">
            <el-date-picker
              v-model="dataForm.endTime"
              :disabled="pageType === 2"
              type="date"
              :placeholder="$t('live.chooseEndDate')"
              value-format="YYYY-MM-DD"
              style="width:140px"
            />
            <el-time-select
              v-model="endTimeValue"
              :class="[endTimeValue ? 'select-time': '']"
              start="00:00"
              step="00:30"
              end="23:30"
              style="width:106px"
              :disabled="pageType === 2"
              :placeholder="$t('time.startTime')"
            />
          </el-form-item>
        </div>
      </el-form-item>
      <!--活动状态-->
      <!--      <el-form-item-->
      <!--        :label="$t('combo.comboStatus')+':'"-->
      <!--        prop="status"-->
      <!--        v-if="dataForm.status === 1 || dataForm.status === 0"-->
      <!--        :required="true"-->
      <!--      >-->
      <!--        <el-radio-group v-model="dataForm.status">-->
      <!--          <el-radio :label="1">{{ $t("groups.turnOn") }}</el-radio>-->
      <!--          <el-radio :label="0">{{ $t("station.close") }}</el-radio>-->
      <!--        </el-radio-group>-->
      <!--      </el-form-item>-->
      <!--套餐主商品-->
      <el-form-item
        :label="$t('combo.comboMainProd') + ':'"
        :required="true"
        style="width: 100%"
      >
        <!--主商品表格-->
        <comboProdTable
          ref="mainProdTableRef"
          :page-type="pageType"
          :type="1"
          :limit="1"
          :mold="1"
          :is-active="1"
          :main-prod-id="matchProdId"
          @refresh-select-prods="selectMainProd"
          @refresh-delete-handle="deleteHandle"
        />
      </el-form-item>
      <!--套餐搭配商品-->
      <el-form-item :label="$t('combo.comboMatchingProd') + ':'">
        <!--搭配商品表格-->
        <comboProdTable
          ref="matchingProdTableRef"
          :page-type="pageType"
          :type="2"
          :limit="4"
          :is-active="0"
          :ban-sku-ids="mainSkuIds"
          :main-prod-id="mainProdId"
          @refresh-select-prods="selectMatchingProds"
          @refresh-delete-handle="deleteMatchHandle"
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="back()"
        >
          {{
            $t("shopFeature.edit.back")
          }}
        </div>
        <div
          v-if="pageType === 1"
          class="default-btn primary-btn"
          @click="dataFormSubmit()"
        >
          {{
            $t("crud.filter.submitBtn")
          }}
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import comboProdTable from './components/prod-table.vue'
import { nextTick, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const Data = reactive({
  dataForm: {
    comboId: 0,
    name: '',
    startTime: '',
    endTime: '',
    mainProd: '',
    matchingProds: []
  },
  pageType: 1, // 1：新增/编辑 2：查看
  mainSkuIds: [], // 主商品skuId列表
  mainProdId: [], // 主商品id
  mainProdIds: [],
  matchProdId: [], // 搭配商品id
  matchingSkuIds: [], // 搭配商品skuId列表
  page: {
    total: 0, // 总页数
    currentPage: 1, // 当前页数
    pageSize: 10 // 每页显示多少条
  },
  errorTip: false,
  dataListSelections: [],
  prodsSelectVisible: false,
  startTimeValue: '',
  endTimeValue: ''
})
const { dataForm, pageType, mainSkuIds, mainProdId, matchProdId, startTimeValue, endTimeValue } = toRefs(Data)

const validName = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('combo.nameNotEmpty')))
  } else {
    callback()
  }
}

const validateTime = (rule, value, callback) => {
  if (rule.field === 'startTime' && (!Data.startTimeValue || !Data.dataForm.startTime)) {
    callback(new Error($t('formData.startTimeCannotBeEmpty')))
  }
  if (rule.field === 'endTime' && (!Data.endTimeValue || !Data.dataForm.endTime)) {
    callback(new Error($t('formData.endTimeCannotBeEmpty')))
  }
  const startTime = Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00'
  const endTime = Data.dataForm.endTime + ' ' + Data.endTimeValue + ':00'
  if (rule.field === 'startTime' && Date.parse(startTime) >= Date.parse(endTime)) {
    callback(new Error($t('marketing.timeCanThanOrEqualTo')))
  }
  if ((Data.dataForm.comboId === 0 || Data.dataForm.status === 1) && rule.field === 'endTime' && new Date() > Date.parse(endTime)) {
    callback(new Error($t('groups.endTime')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  name: [
    { required: true, message: $t('combo.nameNotEmpty'), trigger: 'blur' },
    { validator: validName, trigger: 'blur' }
  ],
  activityDate: [
    { required: true, message: $t('shop.titCanNoBlank'), trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: $t('formData.startTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: $t('formData.endTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ]
})

const route = useRoute()
const commonStore = useCommonStore()
onMounted(() => {
  const comboId = route.query.comboId ? route.query.comboId : 0
  const pageType = route.query.pageType ? route.query.pageType : 1
  init(parseInt(comboId))
  Data.pageType = parseInt(pageType)
  const title = parseInt(comboId) ? (Data.pageType === 1 ? $t('combo.editCombo') : $t('combo.viewCombo')) : $t('combo.addCombo')
  commonStore.replaceSelectMenu(title)
})

const dataFormRef = ref()
// 获取数据列表
const init = (comboId) => {
  Data.dataForm.comboId = comboId || 0
  nextTick(() => {
    dataFormRef.value.resetFields()
    const datetimeRange = getDateTimeRange()
    Data.dataForm.startTime = datetimeRange.startTime
    Data.dataForm.endTime = datetimeRange.endTime
    Data.startTimeValue = datetimeRange.currentTime
    Data.endTimeValue = datetimeRange.currentTime
    if (Data.dataForm.comboId && Data.dataForm.comboId !== '0') {
      getDataInfo()
    }
  })
}

const { proxy } = getCurrentInstance()
const mainProdTableRef = ref()
const matchingProdTableRef = ref()
// 获取套餐信息
const getDataInfo = () => {
  http({
    url: http.adornUrl(`/shop/combo/info/${Data.dataForm.comboId}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    Data.dataForm = data
    Data.startTimeValue = Data.dataForm.startTime ? Data.dataForm.startTime.substring(11, Data.dataForm.startTime.length - 3) : ''
    Data.endTimeValue = Data.dataForm.endTime ? Data.dataForm.endTime.substring(11, Data.dataForm.endTime.length - 3) : ''
    Data.dataForm.startTime = getParseTime(Data.dataForm.startTime, '{y}-{m}-{d}')
    Data.dataForm.endTime = getParseTime(Data.dataForm.endTime, '{y}-{m}-{d}')
    if (data.matchingProds.length) {
      data.matchingProds.forEach(item => {
        Data.matchProdId.push(item.prodId)
      })
    }
    Data.mainProdId.push(data.mainProdId)

    proxy.$forceUpdate()
    nextTick(() => {
      mainProdTableRef.value.init([data.mainProd])
      matchingProdTableRef.value.init(data.matchingProds)
    })
  })
}

// 主商品选择更新回调
const selectMainProd = (prodItems) => {
  if (!prodItems.length) {
    return
  }
  if (Data.mainProdId.length) {
    const id = Data.mainProdId.find((value) => {
      return value === prodItems[0].prodId
    })
    if (id === undefined) {
      Data.mainProdId.push(prodItems[0].prodId)
    }
  } else {
    Data.mainProdId.push(prodItems[0].prodId)
  }
}

// 主删除商品回调
const deleteHandle = (id) => {
  const findIndex = Data.mainProdId.findIndex(item => {
    return item === id
  })
  Data.mainProdId.splice(findIndex, 1)
}

// 搭配删除商品回调
const deleteMatchHandle = (id) => {
  const findIndex = Data.matchProdId.findIndex(item => {
    return item === id
  })
  Data.matchProdId.splice(findIndex, 1)
}

// 搭配商品选择更新回调
const selectMatchingProds = (prodItems) => {
  if (Data.matchProdId.length) {
    Data.matchProdId = prodItems.map(x => x.prodId)
  } else {
    prodItems.forEach(item => {
      Data.matchProdId.push(item.prodId)
    })
  }
}

// 表单提交
const dataFormSubmit = () => {
  if (Data.isSubmit) {
    return
  }
  Data.isSubmit = true
  dataFormRef.value.validate((valid) => {
    const mainProds = mainProdTableRef.value.verifyDataForm()
    const matchingProds = matchingProdTableRef.value.verifyDataForm()
    if (!mainProds || !matchingProds) {
      Data.isSubmit = false
      return
    }
    if (mainProds[0].leastNum <= 1 && matchingProds.length === 0) {
      ElMessage({
        message: $t('tip.select') + $t('combo.comboMatchingProd'),
        type: 'warning',
        duration: 1500
      })
      Data.isSubmit = false
      return
    }
    if (valid) {
      const startTime = Data.dataForm.startTime
      const endTime = Data.dataForm.endTime
      Data.dataForm.startTime = Data.dataForm.startTime && Data.startTimeValue ? Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00' : ''
      Data.dataForm.endTime = Data.dataForm.endTime && Data.endTimeValue ? Data.dataForm.endTime + ' ' + Data.endTimeValue + ':00' : ''
      http({
        url: http.adornUrl('/shop/combo'),
        method: Data.dataForm.comboId && Data.dataForm.comboId !== '0' ? 'put' : 'post',
        data: http.adornData({
          comboId: Data.dataForm.comboId || undefined,
          name: Data.dataForm.name,
          startTime: Data.dataForm.startTime,
          endTime: Data.dataForm.endTime,
          status: Data.dataForm.status,
          mainProd: mainProds[0],
          matchingProds
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            Data.isSubmit = false
            back()
          }
        })
      }).catch(({ e }) => {
        Data.isSubmit = false
      })
      Data.dataForm.startTime = startTime
      Data.dataForm.endTime = endTime
    } else {
      Data.isSubmit = false
    }
  })
}

const router = useRouter()
const back = () => {
  router.push('/marketing/combo/index')
}
</script>

<style lang="scss" scoped>
.page-coupon-add-or-update {
  .coupon-input {
    width: 220px;
  }

  .form-box {
    margin-left: 40px;
  }

  :deep(.el-select .el-input__suffix-inner){
      display: none;
    }
  .select-time:hover :deep(.el-input__suffix-inner){
    display: inline-flex;
  }
}

.date-picker {
  display: flex;
}
</style>
